<template>
  <div class="container">
    <el-card class="box-card" shadow="always">
      <div>
        <div style="float: left">
          <el-form inline @submit.native.prevent="search">
            <el-form-item label="搜索">
              <el-input
                v-model="searchForm.queryConditions"
                clearable
                placeholder="用户名/手机"
                prefix-icon="el-icon-search"
                size="medium"
                style="width: 150px"
              />
            </el-form-item>
            <el-form-item label="组织">
              <el-select
                v-model="organizationList.organizeName"
                clearable
                placeholder="全部"
                style="width: 100px"
                @change="organizationSelected"
              >
                <el-option
                  v-for="item in organizationList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.organizeName"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="角色">
              <el-select
                v-model="roleList.roleNme"
                clearable
                placeholder="全部"
                style="width: 100px"
                @change="roleSelected"
              >
                <el-option
                  v-for="item in roleList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.role"
                />
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button native-type="submit" size="medium" type="primary"
                >搜索</el-button
              >
            </el-form-item>
          </el-form>
        </div>
        <div style="float: right">
          <el-button icon="el-icon-download" type="primary" class="btn">
            <a download :href="exportUrl"> 导出 </a>
          </el-button>
          <el-button
            type="danger"
            @click="deleteAllNonStaff()"
            icon="el-icon-remove-outline"
            class="btn"
          >
            批量删除
          </el-button>
          <el-button
            class="btn"
            type="primary"
            icon="el-icon-circle-plus-outline"
            @click="addManagerDialog"
            >添加</el-button
          >
        </div>
      </div>
      <div>
        <el-table
          :data="list"
          border
          style="width: 100%"
          @selection-change="handleSelectChange"
          v-loading="nonStaffLoading"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column
            type="index"
            width="50"
            label="序号"
            align="center"
          />
          <el-table-column label="头像" width="70" align="center">
            <template slot-scope="scope">
              <el-avatar :src="scope.row.avatar"></el-avatar>
            </template>
          </el-table-column>

          <el-table-column prop="username" label="用户名" align="center" />
          <el-table-column prop="mobilePhone" label="手机号" align="center" />
          <el-table-column label="归属组织" align="center">
            <template slot-scope="scope">
              {{ scope.row.organization.organizeName }}
            </template>
          </el-table-column>
          <el-table-column label="组织描述" align="center">
            <template slot-scope="scope">
              {{ scope.row.organization.description }}
            </template>
          </el-table-column>
          <el-table-column label="账号角色" align="center">
            <template slot-scope="scope">
              {{ scope.row.role.role }}
            </template>
          </el-table-column>
          <el-table-column label="角色描述" align="center">
            <template slot-scope="scope">
              {{ scope.row.role.description }}
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            fixed="right"
            width="250"
          >
            <template slot-scope="scope">
              <el-tooltip content="查看信息" placement="top">
                <el-button
                  size="mini"
                  icon="el-icon-search"
                  circle
                  @click="showDialog(scope.row)"
                />
              </el-tooltip>
              <el-tooltip content="编辑信息" placement="top">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  circle
                  @click="editManagerDialog(scope.row)"
                />
              </el-tooltip>
              <el-tooltip content="还原最初密码" placement="top">
                <el-button
                  size="mini"
                  type="warning"
                  icon="el-icon-refresh"
                  circle
                  @click="refreshPassword(scope.row.id)"
                />
              </el-tooltip>
              <el-tooltip content="删除编外人员" placement="top">
                <el-button
                  size="mini"
                  el-button
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  @click="deleteNonStaff(scope.row)"
                />
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          :current-page="paging.current"
          :page-sizes="paging.pageSizes"
          :page-size="paging.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="paging.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <Dialog
        :visible="nonStaffPersonInfoVisible"
        :info="nonStaffPersonInfo"
        @cancel="cancel"
      />
      <edit-dialog
        :index="index"
        :organization-list="organizationList"
        :title="dialogTitle"
        :visible="editDialogVisible"
        :non-staff-info="nonStaffPersonInfo"
        @cancel="cancel"
        @ok="ok"
      />
    </el-card>
  </div>
</template>

<script>
import {
  queryAll,
  delNonStaff,
  addNonStaff,
  modifyNonStaff,
  getNonStaffRoles,
} from "@/api/nonStaff.js";
import { resetPassword } from "@/api/common";
import { getAllOrganizationInfos } from "@/api/organization";
import Dialog from "./components/Dialog";
import EditDialog from "./components/editDialog";

export default {
  name: "PurchaserManage",
  components: { Dialog, EditDialog },
  data() {
    return {
      searchForm: {
        queryConditions: "",
        organizeId: "",
      },
      organizationList: [],
      roleList: [],
      list: [],
      paging: {
        total: 0,
        current: 1,
        pageSizes: [5, 10, 15],
        size: 5,
      },
      nonStaffPersonInfoVisible: false,
      nonStaffPersonInfo: {},
      editDialogVisible: false,
      nonStaffLoading: false,
      dialogTitle: "",
      index: 0, // 0 添加；1 编辑；2 查看信息
      multipleSelection: [],
      // headers: {
      //   Authorization: getToken(),
      // },
    };
  },
  computed: {
    exportUrl() {
      return (
        process.env.VUE_APP_BASE_API + "/exportNonStaffExcel" 
      );
    },
  },
  created() {
    this.nonStaffLoading = true;
    this.getData();
    this.getOrganizations();
    this.getRoles();
    // console.log(getToken())
  },
  methods: {
    async getOrganizations() {
      const result = await getAllOrganizationInfos();
      this.organizationList = result.data;
    },
    async getRoles() {
      const result = await getNonStaffRoles();
      this.roleList = result.data;
    },
    search() {
      this.paging.current = 1;
      this.nonStaffLoading = true;
      this.getData();
    },
    getData() {
      const form = {
        ...this.searchForm,
        page: this.paging.current,
        pageSize: this.paging.size,
      };
      queryAll(form)
        .then(({ data }) => {
          console.log(data);
          this.list = data.nonStaffs;
          //this.paging.size = data.size
          this.paging.total = data.totalCount;
          this.nonStaffLoading = false;
        })
        .catch((err) => {
          // 如果没有数据就显示为空
          this.list = [];
          // 返还每页显示的条数
          //this.paging.size = res.data.size;
          this.paging.total = 0;
          this.nonStaffLoading = false;
        });
    },
    handleSizeChange(val) {
      this.paging.current = 1;
      this.paging.size = val;
      this.getData();
    },
    handleCurrentChange(val) {
      this.paging.current = val;
      this.getData();
    },
    showDialog(row) {
      console.log("@@@row:", row);
      this.nonStaffPersonInfoVisible = true;
      this.nonStaffPersonInfo = this.extendCopy(row);
      console.log("@@@nonStaffPersonInfo:", this.nonStaffPersonInfo);
      this.index = 2;
    },
    refreshPassword(accountId) {
      console.log(accountId);
      this.$confirm("将还原该账号密码,此操作不可逆 是否确定?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const result = await resetPassword({ accountId: accountId });
          console.log(result);
          if (result.code === 200) {
            this.$message({
              type: "success",
              message: "还原成功!",
            });
            this.getData();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "操作取消",
          });
        });
    },
    // 获取到选中的所有数据
    handleSelectChange(val) {
      this.multipleSelection = [];
      val.forEach((value) => {
        this.multipleSelection.push(value.id);
      });

      console.log(this.multipleSelection);
    },
    deleteNonStaff(row) {
      this.$confirm("此操作将永久删除这条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const ids = [];
          ids.push(row.id)
          const result = await delNonStaff({
            ids: ids,
            accountId: this.$store.getters.accountId,
          });
          console.log(result);
          if (result.code === 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getData();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    deleteAllNonStaff() {
      if (this.multipleSelection.length === 0) return;
      this.$confirm("此操作将永久删除这条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const result = await delNonStaff({
            ids: this.multipleSelection,
            accountId: this.$store.getters.accountId,
          });
          console.log(result);
          if (result.code === 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getData();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },


    organizationSelected(val) {
      this.searchForm.organizeId = val;
      this.search();
    },
    roleSelected(val) {
      this.searchForm.roleId = val;
      this.search();
    },
    editManagerDialog(row) {
      this.dialogTitle = "编辑编外人员信息";
      this.editDialogVisible = true;
      this.nonStaffPersonInfo = this.extendCopy(row);
      this.index = 1;
    },
    // 对象的深拷贝
    // 对象进行深拷贝，否则“编辑”框内修改内容也会影响到页面
    extendCopy(p) {
      var c = {};
      for (var i in p) {
        c[i] = p[i];
      }
      return c;
    },
    addManagerDialog() {
      this.dialogTitle = "添加编外人员";
      this.editDialogVisible = true;
      this.index = 0;
    },
    cancel() {
      if (this.index === 2) {
        this.nonStaffPersonInfoVisible = false;
      } else {
        this.editDialogVisible = false;
      }
      this.index = 0;
    },
    editnonStaffPersonInfo(data) {
      // eslint-disable-next-line no-async-promise-executor
      return new Promise(async (resolve, reject) => {
        if (this.index) {
          // 编辑信息
          // console.log(val)
          const result = await modifyNonStaff(data);
          // console.log(res)
          if (result.code === 200) {
            this.$message.success("修改成功");
            resolve(result);
          } else {
            this.$message.error("修改失败，请重试");
            reject(result);
          }
        } else {
          const result = await addNonStaff(data);
          // console.log(res)
          if (result.code === 200) {
            this.$message.success("添加成功");
            resolve(result);
          } else {
            this.$message.error("添加失败，请重试");
            reject(result);
          }
        }
      });
    },
    async ok(val) {
      const response = await this.editnonStaffPersonInfo(val);
      console.log(response);
      if (response.code === 200) {
        this.editDialogVisible = false;
        this.getData();
        this.index = 0;
      }
    },
    // onSuccess(response, file, fileList) {
    //   console.log(response);
    //   if (response.code !== 200) {
    //     this.$message.error("上传失败，请重试");
    //   } else {
    //     this.$message.success("上传成功");
    //     this.getData();
    //   }
    // },
    // onError(error, file, fileList) {
    //   console.log(error);
    // },
  },
};
</script>
<style lang="scss" scoped>
.el-pagination {
  margin-top: 20px;
  text-align: right;
}
.btn {
  float: right;
  margin-left: 20px;
}
</style>
